<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SimpleMindMap 思维导图应用</title>
    <!-- 引入 simple-mind-map 样式 -->
    <link rel="stylesheet" href="css/simpleMindMap.esm.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            display: flex;
            height: 100vh;
            background-color: #f5f7fa;
            color: #333;
            overflow: hidden;
        }
        
        .sidebar {
            width: 300px;
            background-color: #2c3e50;
            color: white;
            display: flex;
            flex-direction: column;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }
        
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #34495e;
            text-align: center;
        }
        
        .sidebar-header h1 {
            font-size: 1.5rem;
            margin-bottom: 10px;
        }
        
        #minder-container * {
            margin: 0;
            padding: 0;
        }
        
        .new-map-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        
        .new-map-btn:hover {
            background-color: #2980b9;
        }
        
        .map-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        
        .map-item {
            background-color: #34495e;
            padding: 12px;
            margin-bottom: 10px;
            border-radius: 5px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.3s;
        }
        
        .map-item:hover {
            background-color: #3d566e;
        }
        
        .map-item.active {
            background-color: #3498db;
        }
        
        .map-actions {
            display: flex;
            gap: 5px;
        }
        
        .map-actions button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            padding: 5px;
            border-radius: 3px;
            transition: background-color 0.3s;
        }
        
        .map-actions button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .toolbar {
            background-color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        .toolbar-left, .toolbar-right {
            display: flex;
            gap: 10px;
        }
        
        .toolbar-btn {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
        }
        
        .toolbar-btn:hover {
            background-color: #e9ecef;
        }
        
        .mind-map-container {
            flex: 1;
            overflow: hidden;
            position: relative;
            background: #f8f9fa;
        }
        
        #minder-container {
            width: 100%;
            height: 100%;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 100;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-header h2 {
            font-size: 1.5rem;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #777;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
        }
        
        .form-group textarea {
            height: 100px;
            resize: vertical;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
        }
        
        .btn-secondary {
            background-color: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #7f8c8d;
        }
        
        .status-bar {
            background-color: white;
            padding: 5px 20px;
            border-top: 1px solid #dee2e6;
            font-size: 0.9rem;
            color: #6c757d;
            display: flex;
            justify-content: space-between;
        }
        
        .shortcuts {
            position: fixed;
            bottom: 10px;
            right: 10px;
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            font-size: 0.8rem;
        }
        
        .shortcuts h3 {
            margin-bottom: 5px;
        }
        
        .shortcuts ul {
            list-style-type: none;
        }
        
        .shortcuts li {
            margin-bottom: 3px;
        }
        
        .shortcut-key {
            display: inline-block;
            background-color: #f1f1f1;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 0.7rem;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .notification.show {
            opacity: 1;
        }
        
        /* SimpleMindMap 样式 */
        .smm-node {
            cursor: pointer;
        }
        
        /* 确保 SimpleMindMap 的 SVG 容器填满整个区域 */
        #minder-container svg {
            display: block;
            width: 100% !important;
            height: 100% !important;
        }
        
        /* SimpleMindMap 的根容器样式 */
        #minder-container > div {
            width: 100% !important;
            height: 100% !important;
        }
        
        /* 确保思维导图绘制层填满容器 */
        .smm-canvas {
            width: 100% !important;
            height: 100% !important;
        }
        
        /* 文本编辑框样式优化 - 尽量使用自适应 */
        .smm-text-edit,
        .smm-node-text-edit,
        .editTool,
        .richTextEdit,
        [contenteditable="true"] {
            box-sizing: border-box !important;
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h1>SimpleMindMap 思维导图</h1>
            <button class="new-map-btn" id="newMapBtn">新建导图</button>
        </div>
        <div class="map-list" id="mapList">
            <!-- 思维导图列表将在这里动态生成 -->
        </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
        <div class="toolbar">
            <div class="toolbar-left">
                <button class="toolbar-btn" id="saveBtn">保存</button>
                <button class="toolbar-btn" id="exportBtn">导出 JSON</button>
                <button class="toolbar-btn" id="exportPngBtn">导出 PNG</button>
                <button class="toolbar-btn" id="exportSvgBtn">导出 SVG</button>
                <button class="toolbar-btn" id="exportPdfBtn">导出 PDF</button>
                <button class="toolbar-btn" id="importBtn">导入</button>
            </div>
            <div class="toolbar-right">
                <button class="toolbar-btn" id="undoBtn">撤销</button>
                <button class="toolbar-btn" id="redoBtn">重做</button>
                <button class="toolbar-btn" id="themeBtn">主题</button>
            </div>
        </div>
        <div class="mind-map-container">
            <div id="minder-container"></div>
        </div>
        <div class="status-bar">
            <div>自动保存: <span id="autoSaveStatus">已启用</span></div>
            <div>当前导图: <span id="currentMapName">未选择</span></div>
        </div>
    </div>
    
    <!-- 新建/编辑思维导图模态框 -->
    <div class="modal" id="mapModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">新建思维导图</h2>
                <button class="close-btn" id="closeModalBtn">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="mapName">导图名称</label>
                    <input type="text" id="mapName" placeholder="输入导图名称">
                </div>
                <div class="form-group">
                    <label for="mapDescription">导图描述</label>
                    <textarea id="mapDescription" placeholder="输入导图描述（可选）"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="cancelBtn">取消</button>
                <button class="btn btn-primary" id="saveMapBtn">保存</button>
            </div>
        </div>
    </div>
    
    <!-- 快捷键提示 -->
    <div class="shortcuts">
        <h3>快捷键</h3>
        <ul>
            <li><span class="shortcut-key">Ctrl+S</span> 保存导图</li>
            <li><span class="shortcut-key">Enter</span> 添加兄弟节点</li>
            <li><span class="shortcut-key">Tab</span> 添加子节点</li>
            <li><span class="shortcut-key">Delete</span> 删除节点</li>
            <li><span class="shortcut-key">Ctrl+Z</span> 撤销</li>
            <li><span class="shortcut-key">Ctrl+Y</span> 重做</li>
        </ul>
    </div>

    <!-- 通知 -->
    <div class="notification" id="notification"></div>

    <!-- 引入 simple-mind-map -->
    <script src="js/simpleMindMap.umd.js"></script>
    <script>
        // 思维导图管理类
        class MindMapManager {
            constructor() {
                this.maps = JSON.parse(localStorage.getItem('mindMaps')) || [];
                this.currentMapId = null;
                this.minder = null;
                this.currentTheme = 'default';
                this.autoSaveFlag = false;
                this.tempSaveTimer = null; // 临时保存定时器
                this.init();
            }
            
            init() {
                this.renderMapList();
                this.bindEvents();
                this.setupMindMap();
                this.setupAutoSave();
                this.loadLastTempMap(); // 加载上次的临时思维导图
            }
            
            // 清理文本中的 HTML 标签
            cleanText(text) {
                if (!text) return '';
                // 删除所有 HTML 标签，只保留纯文本
                const div = document.createElement('div');
                div.innerHTML = text;
                return div.textContent || div.innerText || '';
            }
            
            // 清理思维导图数据中的 HTML 标签
            cleanMindMapData(data) {
                if (!data) return data;
                
                // 递归清理节点数据
                const cleanNode = (node) => {
                    if (node.data && node.data.text) {
                        node.data.text = this.cleanText(node.data.text);
                    }
                    if (node.children && Array.isArray(node.children)) {
                        node.children.forEach(child => cleanNode(child));
                    }
                    return node;
                };
                
                return cleanNode(JSON.parse(JSON.stringify(data)));
            }
            
            // 渲染思维导图列表
            renderMapList() {
                const mapList = document.getElementById('mapList');
                mapList.innerHTML = '';
                
                if (this.maps.length === 0) {
                    mapList.innerHTML = '<p style="text-align: center; padding: 20px; color: #95a5a6;">暂无思维导图</p>';
                    return;
                }
                
                this.maps.forEach(map => {
                    const mapItem = document.createElement('div');
                    mapItem.className = `map-item ${this.currentMapId === map.id ? 'active' : ''}`;
                    mapItem.innerHTML = `
                        <div class="map-info">
                            <div class="map-name">${map.name}</div>
                            <div class="map-date">${new Date(map.updatedAt).toLocaleDateString()}</div>
                        </div>
                        <div class="map-actions">
                            <button class="edit-map" data-id="${map.id}">编辑</button>
                            <button class="delete-map" data-id="${map.id}">删除</button>
                        </div>
                    `;
                    mapList.appendChild(mapItem);
                    
                    // 添加点击事件
                    mapItem.addEventListener('click', (e) => {
                        if (!e.target.classList.contains('edit-map') && !e.target.classList.contains('delete-map')) {
                            this.loadMap(map.id);
                        }
                    });
                    
                    // 编辑按钮
                    mapItem.querySelector('.edit-map').addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.openEditModal(map.id);
                    });
                    
                    // 删除按钮
                    mapItem.querySelector('.delete-map').addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.deleteMap(map.id);
                    });
                });
            }
            
            // 绑定事件
            bindEvents() {
                // 新建思维导图按钮
                document.getElementById('newMapBtn').addEventListener('click', () => {
                    this.openCreateModal();
                });
                
                // 模态框相关按钮
                document.getElementById('closeModalBtn').addEventListener('click', () => {
                    this.closeModal();
                });
                
                document.getElementById('cancelBtn').addEventListener('click', () => {
                    this.closeModal();
                });
                
                document.getElementById('saveMapBtn').addEventListener('click', () => {
                    this.saveMapFromModal();
                });
                
                // 工具栏按钮
                document.getElementById('saveBtn').addEventListener('click', () => {
                    this.saveCurrentMap();
                });
                
                document.getElementById('exportBtn').addEventListener('click', () => {
                    this.exportMap();
                });
                
                document.getElementById('exportPngBtn').addEventListener('click', () => {
                    this.exportAsPng();
                });
                
                document.getElementById('exportSvgBtn').addEventListener('click', () => {
                    this.exportAsSvg();
                });
                
                document.getElementById('exportPdfBtn').addEventListener('click', () => {
                    this.exportAsPdf();
                });
                
                document.getElementById('importBtn').addEventListener('click', () => {
                    this.importMap();
                });
                
                document.getElementById('undoBtn').addEventListener('click', () => {
                    if (this.minder) {
                        this.minder.execCommand('BACK');
                    }
                });
                
                document.getElementById('redoBtn').addEventListener('click', () => {
                    if (this.minder) {
                        this.minder.execCommand('FORWARD');
                    }
                });
                
                document.getElementById('themeBtn').addEventListener('click', () => {
                    this.changeTheme();
                });
                
                // Ctrl+S 保存快捷键
                document.addEventListener('keydown', (e) => {
                    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                        e.preventDefault();
                        this.handleSave();
                    }
                });
                
                // 键盘快捷键 - SimpleMindMap 已内置支持，不需要手动绑定
                // SimpleMindMap 默认支持的快捷键：
                // Enter: 添加兄弟节点
                // Tab: 添加子节点
                // Delete/Backspace: 删除节点
                // Ctrl+Z: 撤销
                // Ctrl+Y: 重做
                // 等等...
                
                // 粘贴图片功能 - SimpleMindMap 有内置支持
                // 可以通过 node.setImage() 方法添加图片
            }
            
            // 设置思维导图
            setupMindMap() {
                // 检查容器元素
                const container = document.getElementById('minder-container');
                if (!container) {
                    console.error('找不到容器元素 #minder-container');
                    return;
                }
                
                // 输出容器尺寸信息
                const rect = container.getBoundingClientRect();
                console.log('容器尺寸:', {
                    width: rect.width,
                    height: rect.height,
                    offsetWidth: container.offsetWidth,
                    offsetHeight: container.offsetHeight
                });
                
                // 初始化 SimpleMindMap
                // UMD 包可能将构造函数放在不同的位置
                let MindMapConstructor;
                
                // 尝试多种可能的导出方式
                if (typeof window.simpleMindMap === 'function') {
                    // 直接是构造函数
                    MindMapConstructor = window.simpleMindMap;
                } else if (window.simpleMindMap && typeof window.simpleMindMap.default === 'function') {
                    // ES Module 默认导出包装在 default 中
                    MindMapConstructor = window.simpleMindMap.default;
                } else if (window.MindMap && typeof window.MindMap === 'function') {
                    // 直接挂载在 window.MindMap
                    MindMapConstructor = window.MindMap;
                } else {
                    // 调试信息
                    console.error('SimpleMindMap 加载失败');
                    console.log('window.simpleMindMap:', window.simpleMindMap);
                    console.log('typeof window.simpleMindMap:', typeof window.simpleMindMap);
                    if (window.simpleMindMap) {
                        console.log('window.simpleMindMap 的属性:', Object.keys(window.simpleMindMap));
                    }
                    alert('SimpleMindMap 库加载失败，请检查网络连接后刷新页面重试');
                    return;
                }
                
                console.log('使用的构造函数:', MindMapConstructor);
                
                try {
                    this.minder = new MindMapConstructor({
                        el: container,
                        data: {
                            "data": {
                                "text": "中心主题"
                            },
                            "children": []
                        },
                        layout: 'logicalStructure',
                        theme: 'default',
                        readonly: false,
                        // 确保初始根节点在画布中心
                        initRootNodePosition: ['center', 'center'],
                        // 文本自动换行宽度，设置为较小的值使输入框更紧凑
                        // 0 表示不限制，完全自适应（但可能导致过长）
                        // 推荐值: 150-300，根据实际情况调整
                        textAutoWrapWidth: 70
                    });
                    
                    console.log('SimpleMindMap 实例创建成功:', this.minder);
                    
                    // 监听数据变化，用于自动保存
                    this.minder.on('data_change', () => {
                        if (this.currentMapId) {
                            this.autoSaveFlag = true;
                        }
                        // 临时保存到 localStorage
                        this.tempSaveToLocalStorage();
                    });
                    
                    // 监听节点树渲染完成
                    this.minder.on('node_tree_render_end', () => {
                        console.log('节点树渲染完成');
                    });
                } catch (error) {
                    console.error('创建 SimpleMindMap 实例时出错:', error);
                    alert('初始化思维导图失败: ' + error.message);
                }
            }
            
            // 处理保存操作（支持快捷键和按钮）
            handleSave() {
                if (!this.minder) return;
                
                // 如果当前没有关联的导图，弹窗让用户输入名称
                if (!this.currentMapId) {
                    this.openSaveAsNewModal();
                } else {
                    // 已关联导图，直接保存
                    this.saveCurrentMap();
                }
            }
            
            // 打开"另存为新导图"模态框
            openSaveAsNewModal() {
                if (!this.minder) return;
                
                // 获取根节点文本作为默认名称，并清理 HTML 标签
                const data = this.minder.getData();
                let defaultName = '新思维导图';
                if (data && data.data && data.data.text) {
                    defaultName = this.cleanText(data.data.text);
                }
                
                document.getElementById('modalTitle').textContent = '保存思维导图';
                document.getElementById('mapName').value = defaultName;
                document.getElementById('mapDescription').value = '';
                document.getElementById('mapModal').style.display = 'flex';
                this.editingMapId = null;
                
                // 聚焦到名称输入框
                setTimeout(() => {
                    document.getElementById('mapName').select();
                }, 100);
            }
            
            // 临时保存到 localStorage
            tempSaveToLocalStorage() {
                if (!this.minder) return;
                
                // 使用防抖，避免频繁保存
                clearTimeout(this.tempSaveTimer);
                this.tempSaveTimer = setTimeout(() => {
                    try {
                        const data = this.minder.getData();
                        // 清理数据中的 HTML 标签
                        const cleanedData = this.cleanMindMapData(data);
                        const tempData = {
                            data: cleanedData,
                            timestamp: new Date().toISOString(),
                            currentMapId: this.currentMapId
                        };
                        localStorage.setItem('mindMap_temp', JSON.stringify(tempData));
                        console.log('临时保存成功');
                    } catch (error) {
                        console.error('临时保存失败:', error);
                    }
                }, 1000); // 1秒后保存
            }
            
            // 加载上次的临时思维导图
            loadLastTempMap() {
                if (!this.minder) return;
                
                try {
                    const tempDataStr = localStorage.getItem('mindMap_temp');
                    if (!tempDataStr) return;
                    
                    const tempData = JSON.parse(tempDataStr);
                    
                    // 如果有关联的导图ID，尝试加载该导图
                    if (tempData.currentMapId) {
                        const map = this.maps.find(m => m.id === tempData.currentMapId);
                        if (map) {
                            this.loadMap(tempData.currentMapId);
                            this.showNotification('已加载上次编辑的思维导图');
                            return;
                        }
                    }
                    
                    // 如果没有关联的导图，但有临时数据，加载临时数据
                    if (tempData.data && tempData.data.data) {
                        // 检查是否不是默认的"中心主题"
                        const isDefaultData = tempData.data.data.text === '中心主题' && 
                                             (!tempData.data.children || tempData.data.children.length === 0);
                        
                        if (!isDefaultData) {
                            this.minder.setData(tempData.data);
                            this.showNotification('已恢复上次未保存的思维导图');
                        }
                    }
                } catch (error) {
                    console.error('加载临时思维导图失败:', error);
                }
            }
            
            // 打开创建模态框
            openCreateModal() {
                document.getElementById('modalTitle').textContent = '新建思维导图';
                document.getElementById('mapName').value = '';
                document.getElementById('mapDescription').value = '';
                document.getElementById('mapModal').style.display = 'flex';
                this.editingMapId = null;
            }
            
            // 打开编辑模态框
            openEditModal(mapId) {
                const map = this.maps.find(m => m.id === mapId);
                if (!map) return;
                
                document.getElementById('modalTitle').textContent = '编辑思维导图';
                document.getElementById('mapName').value = map.name;
                document.getElementById('mapDescription').value = map.description || '';
                document.getElementById('mapModal').style.display = 'flex';
                this.editingMapId = mapId;
            }
            
            // 关闭模态框
            closeModal() {
                document.getElementById('mapModal').style.display = 'none';
            }
            
            // 从模态框保存思维导图
            saveMapFromModal() {
                const name = document.getElementById('mapName').value.trim();
                const description = document.getElementById('mapDescription').value.trim();
                
                if (!name) {
                    alert('请输入导图名称');
                    return;
                }
                
                if (this.editingMapId) {
                    // 编辑现有思维导图
                    const mapIndex = this.maps.findIndex(m => m.id === this.editingMapId);
                    if (mapIndex !== -1) {
                        this.maps[mapIndex].name = name;
                        this.maps[mapIndex].description = description;
                        this.maps[mapIndex].updatedAt = new Date().toISOString();
                    }
                } else {
                    // 创建新思维导图 - SimpleMindMap 数据结构
                    const initialData = {
                        "data": {
                            "text": name
                        },
                        "children": []
                    };
                    
                    const newMap = {
                        id: Date.now().toString(),
                        name,
                        description,
                        data: initialData,
                        createdAt: new Date().toISOString(),
                        updatedAt: new Date().toISOString()
                    };
                    
                    this.maps.push(newMap);
                    this.currentMapId = newMap.id;
                }
                
                this.saveToLocalStorage();
                this.renderMapList();
                this.closeModal();
                
                if (!this.editingMapId) {
                    this.loadMap(this.currentMapId);
                }
                
                this.showNotification('导图已保存');
            }
            
            // 加载思维导图
            loadMap(mapId) {
                const map = this.maps.find(m => m.id === mapId);
                if (!map) return;
                
                this.currentMapId = mapId;
                
                try {
                    // 确保数据格式正确，如果没有数据则创建默认数据
                    if (!map.data || !map.data.data) {
                        map.data = {
                            "data": {
                                "text": map.name || "中心主题"
                            },
                            "children": []
                        };
                        this.saveToLocalStorage();
                    }
                    
                    // 使用 SimpleMindMap 的 setData 方法
                    this.minder.setData(map.data);
                    document.getElementById('currentMapName').textContent = map.name;
                    this.renderMapList();
                    this.showNotification(`已加载: ${map.name}`);
                } catch (error) {
                    console.error('加载思维导图失败:', error);
                    this.showNotification('加载失败，数据格式可能不正确');
                }
            }
            
            // 删除思维导图
            deleteMap(mapId) {
                if (confirm('确定要删除这个思维导图吗？')) {
                    this.maps = this.maps.filter(m => m.id !== mapId);
                    
                    if (this.currentMapId === mapId) {
                        this.currentMapId = null;
                        // 清空当前思维导图
                        this.minder.setData({
                            "data": {
                                "text": "中心主题"
                            },
                            "children": []
                        });
                        document.getElementById('currentMapName').textContent = '未选择';
                    }
                    
                    this.saveToLocalStorage();
                    this.renderMapList();
                    this.showNotification('导图已删除');
                }
            }
            
            // 保存当前思维导图
            saveCurrentMap() {
                if (!this.currentMapId) {
                    // 如果没有关联导图，提示保存为新导图
                    this.openSaveAsNewModal();
                    return;
                }
                
                const mapIndex = this.maps.findIndex(m => m.id === this.currentMapId);
                if (mapIndex !== -1) {
                    // 使用 SimpleMindMap 的 getData 方法，并清理 HTML 标签
                    const data = this.minder.getData();
                    this.maps[mapIndex].data = this.cleanMindMapData(data);
                    this.maps[mapIndex].updatedAt = new Date().toISOString();
                    this.saveToLocalStorage();
                    this.renderMapList();
                    
                    // 显示保存成功提示
                    this.showNotification('导图已保存');
                }
            }
            
            // 导出思维导图（JSON格式）
            exportMap() {
                if (!this.currentMapId) {
                    alert('请先选择一个思维导图');
                    return;
                }
                
                const map = this.maps.find(m => m.id === this.currentMapId);
                if (!map) return;
                
                // 清理数据中的 HTML 标签后导出
                const cleanedData = this.cleanMindMapData(map.data);
                const dataStr = JSON.stringify(cleanedData, null, 2);
                const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
                
                const exportFileDefaultName = `${map.name}.json`;
                
                const linkElement = document.createElement('a');
                linkElement.setAttribute('href', dataUri);
                linkElement.setAttribute('download', exportFileDefaultName);
                linkElement.click();
                
                this.showNotification('导图已导出为 JSON');
            }
            
            // 导出为 PNG 图片
            async exportAsPng() {
                if (!this.minder) {
                    alert('请先创建或加载一个思维导图');
                    return;
                }
                
                try {
                    // 检查是否有 doExport 方法
                    if (!this.minder.doExport || !this.minder.doExport.png) {
                        alert('当前 SimpleMindMap 版本不支持 PNG 导出功能，请使用浏览器截图功能');
                        return;
                    }
                    
                    this.showNotification('正在导出 PNG...');
                    
                    // 获取当前导图名称
                    const map = this.maps.find(m => m.id === this.currentMapId);
                    const fileName = map ? map.name : '思维导图';
                    
                    // 导出 PNG，背景透明
                    const data = await this.minder.doExport.png(fileName, true);
                    
                    // 下载图片
                    const a = document.createElement('a');
                    a.href = data;
                    a.download = `${fileName}.png`;
                    a.click();
                    
                    this.showNotification('PNG 导出成功');
                } catch (error) {
                    console.error('PNG 导出失败:', error);
                    alert('PNG 导出失败：' + error.message);
                }
            }
            
            // 导出为 SVG 图片
            async exportAsSvg() {
                if (!this.minder) {
                    alert('请先创建或加载一个思维导图');
                    return;
                }
                
                try {
                    // 检查是否有 doExport 方法
                    if (!this.minder.doExport || !this.minder.doExport.svg) {
                        alert('当前 SimpleMindMap 版本不支持 SVG 导出功能');
                        return;
                    }
                    
                    this.showNotification('正在导出 SVG...');
                    
                    // 获取当前导图名称
                    const map = this.maps.find(m => m.id === this.currentMapId);
                    const fileName = map ? map.name : '思维导图';
                    
                    // 导出 SVG
                    const data = await this.minder.doExport.svg(fileName);
                    
                    // 下载 SVG
                    const a = document.createElement('a');
                    a.href = data;
                    a.download = `${fileName}.svg`;
                    a.click();
                    
                    this.showNotification('SVG 导出成功');
                } catch (error) {
                    console.error('SVG 导出失败:', error);
                    alert('SVG 导出失败：' + error.message);
                }
            }
            
            // 导出为 PDF
            async exportAsPdf() {
                if (!this.minder) {
                    alert('请先创建或加载一个思维导图');
                    return;
                }
                
                try {
                    // 检查是否有 doExport 方法
                    if (!this.minder.doExport || !this.minder.doExport.pdf) {
                        alert('当前 SimpleMindMap 版本不支持 PDF 导出功能，PDF 导出需要额外的插件。建议先导出为 PNG 然后转换为 PDF');
                        return;
                    }
                    
                    this.showNotification('正在导出 PDF...');
                    
                    // 获取当前导图名称
                    const map = this.maps.find(m => m.id === this.currentMapId);
                    const fileName = map ? map.name : '思维导图';
                    
                    // 导出 PDF（注意：PDF 导出可能直接触发下载）
                    await this.minder.doExport.pdf(fileName, true);
                    
                    this.showNotification('PDF 导出成功');
                } catch (error) {
                    console.error('PDF 导出失败:', error);
                    alert('PDF 导出失败：' + error.message);
                }
            }
            
            // 导入思维导图
            importMap() {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = '.json,.smm';
                
                input.onchange = e => {
                    const file = e.target.files[0];
                    const reader = new FileReader();
                    
                    reader.onload = event => {
                        try {
                            const data = JSON.parse(event.target.result);
                            
                            // 验证导入的数据结构 - SimpleMindMap 格式
                            if (!data.data) {
                                alert('导入失败：文件格式不正确，缺少根节点');
                                return;
                            }
                            
                            // 清理导入数据中的 HTML 标签
                            const cleanedData = this.cleanMindMapData(data);
                            
                            const name = file.name.replace(/\.(json|smm)$/, '');
                            const newMap = {
                                id: Date.now().toString(),
                                name,
                                description: '导入的思维导图',
                                data: cleanedData,
                                createdAt: new Date().toISOString(),
                                updatedAt: new Date().toISOString()
                            };
                            
                            this.maps.push(newMap);
                            this.saveToLocalStorage();
                            this.renderMapList();
                            this.loadMap(newMap.id);
                            
                            this.showNotification('导图已导入');
                        } catch (error) {
                            console.error('导入失败:', error);
                            alert('导入失败：文件格式不正确');
                        }
                    };
                    
                    reader.readAsText(file);
                };
                
                input.click();
            }
            
            // 更改主题
            changeTheme() {
                if (!this.minder) return;
                
                // SimpleMindMap 主题列表（需要引入主题插件才能使用更多主题）
                const themes = ['default', 'classic', 'minions', 'pinkGrape', 'mint', 
                               'gold', 'vitalityOrange', 'greenLeaf'];
                const currentTheme = this.currentTheme || 'default';
                const currentIndex = themes.indexOf(currentTheme);
                const nextIndex = (currentIndex + 1) % themes.length;
                
                try {
                    this.minder.setTheme(themes[nextIndex]);
                    this.currentTheme = themes[nextIndex];
                    this.saveCurrentMap();
                    this.showNotification(`主题已切换: ${themes[nextIndex]}`);
                } catch (error) {
                    // 如果主题不存在，回退到默认主题
                    this.minder.setTheme('default');
                    this.currentTheme = 'default';
                    this.showNotification('该主题需要额外插件，已回退到默认主题');
                }
            }
            
            // 设置自动保存
            setupAutoSave() {
                setInterval(() => {
                    if (this.currentMapId && this.minder && this.autoSaveFlag) {
                        this.saveCurrentMap();
                        this.autoSaveFlag = false;
                    }
                }, 30000); // 每30秒自动保存一次
            }
            
            // 保存到本地存储
            saveToLocalStorage() {
                localStorage.setItem('mindMaps', JSON.stringify(this.maps));
            }
            
            // 显示通知
            showNotification(message) {
                const notification = document.getElementById('notification');
                notification.textContent = message;
                notification.classList.add('show');
                
                setTimeout(() => {
                    notification.classList.remove('show');
                }, 3000);
            }
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            new MindMapManager();
        });
    </script>
</body>
</html>